import * as Cesium from 'cesium';
import { ref } from 'vue';

// 环境配置映射
const ENVIRONMENT_CONFIG = {
  'http://10.211.142.110:30980': 'http://10.211.142.117:7083',
  'http://100.90.131.99:30980': 'http://100.70.4.38:7083'
} as const;

// 默认服务器地址
const DEFAULT_SERVER = 'http://100.70.4.38:7083';

// 根据当前URL获取对应的服务器地址
const getServerUrl = (): string => {
  const currentUrl = window.location.href;

  for (const [envUrl, serverUrl] of Object.entries(ENVIRONMENT_CONFIG)) {
    if (currentUrl.includes(envUrl)) {
      return serverUrl;
    }
  }

  return DEFAULT_SERVER;
};

// 瓦片服务URL模板
const TILE_URL_TEMPLATES = {
  raster: '/DOMData/4490/JNRaster/{TileMatrix}/{TileCol}/{TileRow}.png',
  rasterDJ: '/DOMData/4490/JNRasterDJ/{TileMatrix}/{TileCol}/{TileRow}.png',
  pubMap: '/DOMData/4490/JNPubMap/{TileMatrix}/{TileCol}/{TileRow}.png'
} as const;

// 服务器地址
const serverUrl = getServerUrl();

// 瓦片服务URL
const TDT_CIA_W = ref(`${serverUrl}${TILE_URL_TEMPLATES.raster}`);
const TDT_CIA_Y = ref(`${serverUrl}${TILE_URL_TEMPLATES.rasterDJ}`);
const administrative = ref(`${serverUrl}${TILE_URL_TEMPLATES.pubMap}`);

export const token = ref(
  'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5NTNjNDc1OC1iMmI5LTRiZDMtYWZlNy1iODVjNzczNTQwYzAiLCJpZCI6MTE2ODc0LCJpYXQiOjE2Njk5NDg5ODV9.PY_LP0AMif83sTZpQE88vNL99Sw9w1F7w1sICeMCr_4'
);
// 生成瓦片矩阵标签 (1-20)
const tileMatrixLabels = Array.from({ length: 20 }, (_, i) => i + 1);

// 通用瓦片服务配置
const TILE_SERVICE_CONFIG = {
  layer: 'sdimg2017',
  style: 'default',
  format: 'image/png',
  tileMatrixSetID: 'img2017',
  tileMatrixLabels,
  tilingScheme: new Cesium.GeographicTilingScheme()
} as const;

// 创建瓦片服务提供者的工厂函数
const createTileServiceProvider = (url: string) => {
  return new Cesium.WebMapTileServiceImageryProvider({
    url,
    ...TILE_SERVICE_CONFIG
  });
};

// 导出瓦片服务提供者
export const Img = createTileServiceProvider(TDT_CIA_W.value);
export const Img1 = createTileServiceProvider(TDT_CIA_Y.value);
export const ADMIN_S = createTileServiceProvider(administrative.value);
